<script setup lang="ts">
import { onMounted, ref } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { z } from 'zod'
import LoadingContainer from '@/components/common/LoadingContainer.vue'
import message from '@/components/common/message'
import { login } from '@/request/auth'
import AuthInput from './components/AuthInput.vue'

const router = useRouter()
const route = useRoute()
const account = ref('')
const password = ref('')
const isLoading = ref(false)
const isAgree = ref(false)
const accountInput = ref<InstanceType<typeof AuthInput> | null>(null)
const passwordInput = ref<InstanceType<typeof AuthInput> | null>(null)

// 创建Zod校验模式 - 支持手机号或邮箱
const accountSchema = z.string()
  .min(1, '请输入手机号或邮箱')
  .refine(
    (value) => {
      // 手机号验证
      const phoneRegex = /^1[3-9]\d{9}$/
      // 邮箱验证
      const emailRegex = /^[^\s@]+@[^\s@][^\s.@]*\.[^\s@]+$/
      return phoneRegex.test(value) || emailRegex.test(value)
    },
    {
      message: '请输入有效的手机号或邮箱地址',
    },
  )

const passwordSchema = z.string()
  .min(6, '密码至少需要6个字符')
  .max(20, '密码最多20个字符')

// 表单验证状态
const accountValid = ref(false)
const passwordValid = ref(false)

// 处理验证错误
function handleValidationError(field: string, _error: string) {
  if (field === 'account')
    accountValid.value = false
  if (field === 'password')
    passwordValid.value = false
}

// 处理验证成功
function handleValidationSuccess(field: string) {
  if (field === 'account')
    accountValid.value = true
  if (field === 'password')
    passwordValid.value = true
}

// 验证所有输入
function validateAllInputs() {
  let isAllValid = true

  // 验证账号
  if (accountInput.value) {
    const isAccountValid = accountInput.value.forceValidate()
    isAllValid = isAllValid && isAccountValid
  }

  // 验证密码
  if (passwordInput.value) {
    const isPasswordValid = passwordInput.value.forceValidate()
    isAllValid = isAllValid && isPasswordValid
  }

  return isAllValid
}

async function handleLogin() {
  // 先验证所有输入
  const isValid = validateAllInputs()

  if (!isValid) {
    return
  }

  if (!isAgree.value) {
    message.info('请阅读并同意小花狮使用协议和隐私政策')
    return
  }

  try {
    isLoading.value = true
    const info = await login({
      username: account.value,
      password: password.value,
      grant_type: 'password',
    })
    localStorage.setItem('token', info.entry.access_token)
    message.success('登录成功')
    router.push('/')
  }
  catch (error: any) {
    message.error(error)
  }
  finally {
    isLoading.value = false
  }
}

onMounted(() => {
  if (route.query.redirect === 'true')
    message.info('请先登录')
})
</script>

<template>
  <LoadingContainer :loading="isLoading">
    <div class="login-header">
      <h1>验证登录</h1>
    </div>

    <div class="login-inputs">
      <AuthInput
        ref="accountInput" v-model="account" type="phone-email" placeholder="请输入手机号或邮箱" :schema="accountSchema"
        @validation-error="(error) => handleValidationError('account', error)"
        @validation-success="() => handleValidationSuccess('account')"
      />

      <AuthInput
        ref="passwordInput" v-model="password" type="password" placeholder="请输入密码" :schema="passwordSchema"
        @validation-error="(error) => handleValidationError('password', error)"
        @validation-success="() => handleValidationSuccess('password')"
      />

      <div class="login-options">
        <div class="agreement">
          <input id="agree" v-model="isAgree" type="checkbox">
          <label for="agree">已阅读并同意小花狮的<b>使用协议</b>和<b>隐私协议</b></label>
        </div>
      </div>
    </div>

    <button class="login-button" :disabled="isLoading" @click="handleLogin">
      登录
    </button>

    <div class="auth-links">
      <div class="verify-code-link">
        <a @click="router.push('/auth/verify-login')">验证码登录</a>
      </div>
      <div class="register-link">
        还没有账号? <a @click="router.push('/auth/register')">立即注册</a>
      </div>
    </div>
  </LoadingContainer>
</template>

<style scoped>
.login-header {
  text-align: center;
  margin-bottom: 50px;
}

.login-header h1 {
  font-size: 28px;
  color: #333;
  margin-bottom: 8px;
}

.login-header p {
  font-size: 16px;
  color: #666;
}

.login-inputs {
  margin-bottom: 24px;
}

.login-options {
  display: flex;
  justify-content: center;
  align-items: center;
  margin-top: 30px;

  .agreement {
    display: flex;
    align-items: center;

    label {
      margin-left: 8px;
      font-size: 14px;
      color: #666;
      line-height: 1px;

      b {
        color: black;
      }
    }
  }
}

.login-button {
  width: 100%;
  height: 50px;
  background-color: #1890ff;
  color: white;
  border: none;
  border-radius: 25px;
  font-size: 16px;
  font-weight: 500;
  cursor: pointer;
  transition: background-color 0.3s;
  margin-bottom: 24px;
}

.login-button:hover {
  background-color: #40a9ff;
}

.login-button:disabled {
  background-color: #bae7ff;
  cursor: not-allowed;
}

.auth-links {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.verify-code-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.verify-code-link a {
  color: #1890ff;
  text-decoration: none;
  cursor: pointer;
}

.register-link {
  text-align: center;
  font-size: 14px;
  color: #666;
}

.register-link a {
  color: #1890ff;
  text-decoration: none;
  cursor: pointer;
}
</style>
